import zmq
import znode
import ioloop

opcount = 1000


def rep_app(environ, in_data):
    global opcount
    print("%d : rep_app got %s" % (opcount, in_data,))
    if opcount < 1:
        stopit()

    opcount -= 1
    return "REP echo %d" % opcount
#app()


def req_app(environ, in_data):
    global opcount
    print("%d : req_app got %s" % (opcount, in_data,))
    if opcount < 1:
        stopit()

    opcount -= 1
    return "REQ echo %d" % opcount
#app()


def stopit():
    """docstring for stopit"""
    print("stopit()")
    io_loop.stop()
#stopit()


def bootstrap():
    """docstring for bootstrap"""
    print("Bootstrap")
    bootstrap.req_node.send("Send some shit")
    #io_loop.add_callback(stopit)
#bootstrap()


def onrecv(env, stuff):
    """docstring for onrecv"""
    #print("onrecv environ:%s, stuff:'%s'" % (env, stuff))
    print("onrecv stuff:'%s'" % (stuff))
    rep_node.send("Response yo!")
#onrecv()

io_loop = ioloop.IOLoop.instance()
io_loop.add_callback(bootstrap)


req_node = znode.znode(req_app, type=zmq.REQ)
rep_node = znode.znode(rep_app, type=zmq.REP)

rep_node.on_recv(onrecv)

bootstrap.req_node = req_node

io_loop.start()
